package edu.cwnu.enterprisemanagement.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.cwnu.enterprisemanagement.common.Result;
import edu.cwnu.enterprisemanagement.untils.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class FilterConfig implements Filter{

    //初始化方法，只调用一次
    @Override
    public void init(jakarta.servlet.FilterConfig filterConfig) throws ServletException {
        log.info("执行init方法...");

        Filter.super.init(filterConfig);
    }

    //拦截请求之后调用，会多次调用
    //过滤器过滤所有资源
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain )
            throws IOException, ServletException {
        log.info("执行doFilter方法...");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求的URL地址

        String url = request.getRequestURI();
        log.info("请求的URL地址：{}", url);

        // 判断拦截的URL地址是否包含login、register等
        // 获取完整的请求路径，考虑context-path
        String fullPath = request.getContextPath() + url;
        if (url.contains("login") || url.contains("register")
                || url.endsWith(".html")
                || url.contains("/swagger")
                || url.contains("/api-docs")
                || fullPath.contains("/swagger")
                || fullPath.contains("/webjars")
                || fullPath.contains("/api-docs")) {
            log.info("合法操作，放行");
            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        //获取请求头中的令牌
        String token = request.getHeader("Authorization");
        log.info("获取到的令牌：{}", token);

        // 判断令牌是否存在，如果不存在，则返回错误结果
        if (!StringUtils.hasLength(token)) {
            log.info("令牌为空，拦截请求");
            // 拦截请求
            handleUnauthorized(response, "未登录状态: 令牌不存在");
            return;
        }

        //校验令牌是否正确
        try {
            JwtUtil.parseToken(token);
            log.info("令牌正确，放行");
        } catch (Exception e) {
            log.info("令牌错误，拦截请求");
            // 拦截请求
            handleUnauthorized(response,"令牌错误");
        }

        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    // 新增：统一处理401响应（避免重复代码）
    private void handleUnauthorized(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json; charset=UTF-8");

        // 构建统一响应体
        Result<String> result = Result.error(401, message);
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }

    //销毁方法，只调用一次
    @Override
    public void destroy() {
        log.info("执行destroy销毁方法...");
        Filter.super.destroy();
    }
}